
package ig.util;

//import it.businesslogic.ireport.gui.MainFrame;
//import it.businesslogic.ireport.util.I18n;
//import it.businesslogic.ireport.util.Misc;
import com.jaspersoft.ireport.designer.IReportConnection;
import com.jaspersoft.ireport.designer.connection.gui.PasswordDialog;
import com.jaspersoft.ireport.designer.utils.Misc;
import com.jaspersoft.ireport.locale.I18n;
import ig.metrica.ui.PrincipalMetrica;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
/**
 *
 * @author  Administrator
 */
//public class JDBCConnection extends it.businesslogic.ireport.IReportConnection {
public class JDBCConnection extends IReportConnection {
    
    private String JDBCDriver;    
    private String username;    
    private String password = null;    
    private String url;    
    private String database;    
    private boolean savePassword;    
    private String name;
    
    /**
     * Holds value of property serverAddress.
     */
    private String serverAddress;
    
    /** Creates a new instance of JDBCConnection */
    
    
    public JDBCConnection() {
    }
    
    /**  This method return an instanced connection to the database.
     *  If isJDBCConnection() return false => getConnection() return null
     *
     */
    public java.sql.Connection getConnection()  {
        try{
            Class.forName(this.getJDBCDriver());
            return DriverManager.getConnection(this.getUrl(),this.getUsername(),this.getPassword());
        }catch(ClassNotFoundException ex){
            ex.printStackTrace();
            showErrorMessage(ex.toString(),"Error");
        }catch(SQLException ex){
            showErrorMessage(ex.toString(),"Error");
        }
        return null;
    }    
    
    @Override
    public void  showErrorMessage(String errorMsg, final String title)
    {
        String[] lines = errorMsg.split("\r\n|\n|\r");

        if (lines.length > 25)
        {
            errorMsg = "";
            for (int i=0; i<25; ++i)
            {
                errorMsg += lines[i]+"\n";
            }
            errorMsg +="\n...";
        }
        
        final String fErrorMsg = errorMsg;
        
        Runnable r = new Runnable() {
                public void run() {
                    //JOptionPane.showMessageDialog(MainFrame.getMainInstance(),fErrorMsg,title,JOptionPane.ERROR_MESSAGE);
                    JOptionPane.showMessageDialog(PrincipalMetrica.getInstance(),fErrorMsg,title,JOptionPane.ERROR_MESSAGE);
                }
            };

        if (!SwingUtilities.isEventDispatchThread())
        {
            try {
                SwingUtilities.invokeAndWait( r );
            } catch (InvocationTargetException ex) {
                ex.printStackTrace();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        else
        {
                r.run();
        }
    }
    
    
    /*  This method return an instanced JRDataDource to the database.
     *  If isJDBCConnection() return true => getJRDataSource() return false
     *
     */
    public net.sf.jasperreports.engine.JRDataSource getJRDataSource() {
        return  new net.sf.jasperreports.engine.JREmptyDataSource();
    }
    
    public boolean isJDBCConnection() {
        return true;
    }
    
    /** Getter for property database.
     * @return Value of property database.
     *
     */
    public java.lang.String getDatabase() {
        return database;
    }
    
    /** Setter for property database.
     * @param database New value of property database.
     *
     */
    public void setDatabase(java.lang.String database) {
        this.database = database;
    }
    
    /** Getter for property JDBCDriver.
     * @return Value of property JDBCDriver.
     *
     */
    public java.lang.String getJDBCDriver() {
        return JDBCDriver;
    }
    
    /** Setter for property JDBCDriver.
     * @param JDBCDriver New value of property JDBCDriver.
     *
     */
    public void setJDBCDriver(java.lang.String JDBCDriver) {
        this.JDBCDriver = JDBCDriver;
    }
    
    /** Getter for property password.
     * @return Value of property password.
     *
     */
    public java.lang.String getPassword() {
        
        if (isSavePassword()) return password;
        else
        {
            // Ask for password...
            try {
                //return it.businesslogic.ireport.gui.PasswordDialog.askPassword();
                return PasswordDialog.askPassword();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return "";
    }
    
    /** Setter for property password.
     * @param password New value of property password.
     *
     */
    public void setPassword(java.lang.String password) {
        this.password = password;
    }
    
    /** Getter for property savePassword.
     * @return Value of property savePassword.
     *
     */
    public boolean isSavePassword() {
        return savePassword;
    }
    
    /** Setter for property savePassword.
     * @param savePassword New value of property savePassword.
     *
     */
    public void setSavePassword(boolean savePassword) {
        this.savePassword = savePassword;
    }
    
    /** Getter for property url.
     * @return Value of property url.
     *
     */
    public java.lang.String getUrl() {
        return url;
    }
    
    /** Setter for property url.
     * @param url New value of property url.
     *
     */
    public void setUrl(java.lang.String url) {
        this.url = url;
    }
    
    /** Getter for property username.
     * @return Value of property username.
     *
     */
    public java.lang.String getUsername() {
        return username;
    }
    
    /** Setter for property username.
     * @param username New value of property username.
     *
     */
    public void setUsername(java.lang.String username) {
        this.username = username;
    }
    
    /*
     *  This method return all properties used by this connection
     */
    public java.util.HashMap getProperties()
    {    
        java.util.HashMap map = new java.util.HashMap();
        map.put("JDBCDriver", Misc.nvl(this.getJDBCDriver(),"") );
        map.put("Url", Misc.nvl(this.getUrl(),""));
        map.put("Database", Misc.nvl(this.getDatabase(),""));
        map.put("Username", Misc.nvl(this.getUsername(),""));
        if (this.isSavePassword())
            map.put("Password", Misc.nvl(this.getPassword(),""));
        else map.put("Password","");
        map.put("SavePassword", ""+this.isSavePassword());
        map.put("ServerAddress", Misc.nvl(this.getServerAddress(),"") );
        
        return map;
    }
    
    public void loadProperties(java.util.HashMap map)
    {
        this.setJDBCDriver( (String)map.get("JDBCDriver"));
        this.setUrl( (String)map.get("Url"));
        this.setDatabase( (String)map.get("Database"));
        this.setUsername( (String)map.get("Username"));
        this.setSavePassword(  (""+map.get("SavePassword")).equals("true") );
        if (this.isSavePassword())
            this.setPassword( Misc.nvl((String)map.get("Password"),""));
        this.setServerAddress( Misc.nvl((String)map.get("ServerAddress"),"") );
        
    }
    
    /**
     * Getter for property serverAddress.
     * @return Value of property serverAddress.
     */
    public String getServerAddress() {
        return this.serverAddress;
    }
    
    /**
     * Setter for property serverAddress.
     * @param serverAddress New value of property serverAddress.
     */
    public void setServerAddress(String serverAddress) {
        this.serverAddress = serverAddress;
    }
    
    
    public String getDescription(){ return I18n.getString("connectionType.jdbc", "Database JDBC connection"); }
    
//    public IReportConnectionEditor getIReportConnectionEditor()
//    {
//        return new JDBCConnectionEditor();
//    }
    
    
    public void test() throws Exception
    {
        // Try the java connection...
        Connection conn = null;
        try {
                conn = getConnection();
                if (conn == null) throw new Exception("");
        } finally {
            // Clean up
            if( conn!=null ) try{ conn.close(); } catch(Exception e) { /* anyone really care? */ }
        }
        JOptionPane.showMessageDialog(PrincipalMetrica.getInstance(),I18n.getString("messages.connectionDialog.connectionTestSuccessful","Connection test successful!"),"",JOptionPane.INFORMATION_MESSAGE);
        return;
    }
}
